package com.contextor.cards.shell.services
{
	import flash.utils.Dictionary;
	
	import mx.controls.Alert;
	import mx.messaging.config.ServerConfig;
	import mx.rpc.AbstractOperation;
	import mx.rpc.AsyncToken;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.RemoteObject;

	public class ServiceController implements IResponder, IServiceController
	{
		[Inject(id="loginSerives")]
		public var service:RemoteObject;
		
		private var tokensDict:Dictionary = new Dictionary();
		
		public function ServiceController()
		{
			
		}
		
		public function sendData(operationName:String, ...args):void
		{
			var operation:AbstractOperation = createOperation(operationName);
			
			var arguments:Array = new Array();
			
			// encode (serialize) arguments
			for (var i:int = 0; i < args.length; i++)
			{
				arguments.push(args[i]);
			}
			
			operation.arguments = arguments;
			
			executeOperation(operation);

		}
		
		protected function executeOperation(operation:AbstractOperation):void
		{
			try
			{
				var token:AsyncToken = operation.send();
				//token.message.timestamp = getTimeStamp(); 
				
				// set self as operation responder to process received result
				token.addResponder(this);
				
				tokensDict[token] = new AsyncTokenInfo(token, operation.name, operation.arguments);
			}
			catch (e:Error)
			{
				fault(e);
			}
		}

		public function result(response:Object):void
		{
			Alert.show("Result");
		}
		
		public function fault(info:Object):void
		{
			var evt:FaultEvent = info as FaultEvent;
			Alert.show("fault " + evt.fault.faultString + "\n" + evt.fault.faultDetail);
		}
		
		protected function createOperation(operationName:String):AbstractOperation
		{
			var operation:AbstractOperation = service.getOperation(operationName);
			
			return operation;        	
		}
	}
}